package com.touchstone.cloudpacs.common.exception;

import com.touchstone.cloudpacs.common.utils.result.ResultEnum;
import com.touchstone.cloudpacs.common.utils.result.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageConversionException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @Description : 统一异常处理
 * @Author : hunter
 * @Date: 2019-07-11 17:18
 **/
@Slf4j
@ControllerAdvice
public class CommonExceptionHandler {

    @ResponseBody
    @ExceptionHandler(BusinessException.class)
    public ResultVO handleException(BusinessException e) {
        log.warn("{}", e.getMessage());
        return ResultVO.fail(e.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultVO validationBodyException(MethodArgumentNotValidException exception) {
        FieldError fieldError = exception.getBindingResult().getFieldError();
        log.warn("参数校验异常:{}({})", fieldError.getDefaultMessage(), fieldError.getField());
        return ResultVO.fail(fieldError.getDefaultMessage());
    }

    @ResponseBody
    @ExceptionHandler(HttpMessageConversionException.class)
    public ResultVO parameterTypeException(HttpMessageConversionException exception) {
        log.warn("参数类型转换错误:{}", exception.getCause().getLocalizedMessage());
        return ResultVO.fail("类型转换错误");
    }

    @ResponseBody
    @ExceptionHandler(BindException.class)
    public ResultVO handleBindException(BindException ex) {
        //校验 除了 requestbody 注解方式的参数校验 对应的 bindingresult 为 BeanPropertyBindingResult
        FieldError fieldError = ex.getBindingResult().getFieldError();
        log.warn("必填校验异常:{}({})", fieldError.getDefaultMessage(), fieldError.getField());
        return ResultVO.fail(fieldError.getDefaultMessage());
    }

    @ResponseBody
    @ExceptionHandler(Exception.class)
    public ResultVO handleException(Exception e) {
        e.printStackTrace();
        log.error("{}: {}", ResultEnum.ERROR.getDesc(), e.getMessage());
        return ResultVO.error();
    }
}
